<?php
	// TODO make this module data-source agnostic, make a config file listing URLs for data services
	
	function addReminder($reminders, $student, $datestring) {
		$reminder = $reminders->addChild("reminder");
		$reminder->addChild("name", $student->name);
		$reminder->addChild("id", $student->id);
		$reminder->addChild("category", $student->category);
		$reminder->addChild("email", $student->email);
		$reminder->addChild("phone", $student->phone);
		$reminder->addChild("date", $datestring);
	}
	
	$rulespath = "../data/dummy-rules.xml";
	$datapath = "../data/dummy-student.xml";
	
	if (file_exists($rulespath) && file_exists($datapath)) {
		header("Content-Type:text/xml");
	
		$data = simplexml_load_file($datapath);
		$rules = simplexml_load_file($rulespath);
		
		$reminders = new SimpleXMLElement("<reminders></reminders>");
		
		foreach($rules->rule as $rule) {
			foreach($data->student as $student) {
				if (strcmp($rule->category, $student->category) == 0) {
					switch ($rule->type) {
						case "fixed":
							addReminder($reminders, $student, $rule->date);
							break;
						case "before";
							$studentdate = date_create($student->end_date);
							$interval = DateInterval::createFromDateString($rule->interval);
							$studentdate->sub($interval);
							addReminder($reminders, $student, $studentdate->format("Y-m-d"));
							break;
						case "after";
							$studentdate = date_create($student->end_date);
							$interval = DateInterval::createFromDateString($rule->interval);
							$studentdate->add($interval);
							addReminder($reminders, $student, $studentdate->format("Y-m-d"));
							break;
					}
				}
			}
		}
		
		echo $reminders->asXML();
	} else {
		exit('Failed to access data.');
	}
?>